package com.zhoug.widget.viewgroup;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.RelativeLayout;


import com.zhoug.widget.R;

import androidx.annotation.Nullable;


/**
 * 根据指定的确认的宽或高 设置宽高比例,默认1:1正方形
 */
@SuppressLint("AppCompatCustomView")
public class SquareLayout extends RelativeLayout {
    private static final int SureWidth = 0;
    private static final int SureHeight = 1;
    private int sure;//0:宽确定高,1:高确定宽
    private float ratio = 1;
    private boolean openSquare = true;

    public SquareLayout(Context context) {
        this(context, null);
    }

    public SquareLayout(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SquareLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SquareLayout);
        sure = typedArray.getInt(R.styleable.SquareLayout_sure, SureWidth);
        int ratioWidth = typedArray.getInt(R.styleable.SquareLayout_ratioWidth, 1);
        int ratioHeight = typedArray.getInt(R.styleable.SquareLayout_ratioHeight, 1);
        openSquare = typedArray.getBoolean(R.styleable.SquareLayout_openSquare, true);
        ratio = (float) ratioWidth / (float) ratioHeight;
        typedArray.recycle();
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (openSquare) {
            if (sure == SureWidth) {
                if (ratio == 1) {
                    super.onMeasure(widthMeasureSpec, widthMeasureSpec);
                } else {
                    int width = MeasureSpec.getSize(widthMeasureSpec);
                    int height = (int) (width / ratio);
                    super.onMeasure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
                            MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
                }

            } else if (sure == SureHeight) {
                if (ratio == 1) {
                    super.onMeasure(heightMeasureSpec, heightMeasureSpec);
                } else {
                    int height = MeasureSpec.getSize(heightMeasureSpec);
                    int width = (int) (height * ratio);
                    super.onMeasure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
                            MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
                }
            }
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }

    }

    public void setOpenSquare(boolean openSquare) {
        this.openSquare = openSquare;
    }

}
